package com.tanovo.service.impl;

import com.tanovo.bo.OauthClientDetailsBo;
import com.tanovo.bo.TokenRequest;
import com.tanovo.bo.UserCore;
import com.tanovo.config.UserInfoContext;
import com.tanovo.domain.*;
import com.tanovo.exception.ServiceException;
import com.tanovo.mapper.ClientMapUserMapper;
import com.tanovo.mapper.OauthClientDetailsMapper;
import com.tanovo.service.IOauthClientDetailsService;
import com.tanovo.service.IResourcesService;
import com.tanovo.service.IRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class OauthClientDetailsServiceImpl implements IOauthClientDetailsService {
    @Autowired
    private OauthClientDetailsMapper oauthClientDetailsMapper;
    @Autowired
    private ClientMapUserMapper clientMapUserMapper;
    @Autowired
    private IOauthClientDetailsService iOauthClientDetailsService;
    @Autowired
    private IResourcesService iResourcesService;
    @Autowired
    private IRoleService iRoleService;

    @Override
    public OauthClientDetails getOauthClientDetails(TokenRequest tokenRequest) {
        OauthClientDetailsExample example = new OauthClientDetailsExample();
        example.createCriteria()
                .andClientIdEqualTo(tokenRequest.getClientId())
                .andDelFlagEqualTo(0);
        List<OauthClientDetails> list = oauthClientDetailsMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void addClient(OauthClientDetails oauthClientDetails) {

        if (oauthClientDetails.getAccessTokenValidity() == null) {
            oauthClientDetails.setAccessTokenValidity(30 * 24 * 60 * 60);
        }
        oauthClientDetails.setDelFlag(0);
        oauthClientDetails.setCreateTime(new Date());
        oauthClientDetails.setUpdateTime(new Date());
        oauthClientDetailsMapper.insertSelective(oauthClientDetails);
    }

    @Override
    public void deleteCient(OauthClientDetails oauthClientDetails) {
        oauthClientDetails.setDelFlag(1);
        oauthClientDetails.setUpdateTime(new Date());
        oauthClientDetails.setUpdateBy(UserInfoContext.getUser().getId().toString());
        oauthClientDetailsMapper.updateByPrimaryKeySelective(oauthClientDetails);
    }

    @Override
    public void updateCient(OauthClientDetails oauthClientDetails) {
        oauthClientDetails.setUpdateTime(new Date());
        oauthClientDetails.setUpdateBy(UserInfoContext.getUser().getId().toString());
        oauthClientDetailsMapper.updateByPrimaryKeySelective(oauthClientDetails);
    }

    @Override
    public List<OauthClientDetails> getCompanyCientList(OauthClientDetails oauthClientDetails) {
        OauthClientDetailsExample example = new OauthClientDetailsExample();
        OauthClientDetailsExample.Criteria criteria= example.createCriteria();
        criteria.andDelFlagEqualTo(0)
                .andCompanyIdEqualTo(oauthClientDetails.getCompanyId());
        if(!StringUtils.isEmpty(oauthClientDetails.getAdditionalInformation())){
            criteria.andAdditionalInformationLike("%"+oauthClientDetails.getAdditionalInformation()+"%");
        }
        example.setOrderByClause("sort_order ASC");
        List<OauthClientDetails> clientDetailsList = oauthClientDetailsMapper.selectByExample(example);
        return clientDetailsList;
    }

    @Override
    public Boolean openFlag(String clientId) {
        UserCore user = UserInfoContext.getUser();
        ClientMapUserExample clientMapUserExample = new ClientMapUserExample();
        clientMapUserExample.createCriteria().andClientIdEqualTo(clientId)
                .andUserIdEqualTo(user.getId().toString())
                .andCompanyIdEqualTo(user.getCompanyId())
                .andDelFlagEqualTo(0)
                .andEnableEqualTo(1);
        List<ClientMapUser> list = clientMapUserMapper.selectByExample(clientMapUserExample);
        if (CollectionUtils.isEmpty(list)) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void deleteCientIdList(List<Integer> idList) {
        for (Integer id : idList) {
            OauthClientDetails oauthClientDetails = new OauthClientDetails();
            oauthClientDetails.setId(id);
            this.deleteCient(oauthClientDetails);
        }
    }

    @Override
    public List<ClientMapUser> getUserClientList(Integer userId, Integer companyId, String clientId) {
        ClientMapUserExample clientMapUserExample = new ClientMapUserExample();
        clientMapUserExample.createCriteria()
                .andClientIdEqualTo(clientId)
                .andUserIdEqualTo(userId.toString())
                .andCompanyIdEqualTo(companyId)
                .andDelFlagEqualTo(0);
        return clientMapUserMapper.selectByExample(clientMapUserExample);
    }

    @Override
    public void bindSuperadmin(OauthClientDetailsBo clientDetailsBo) {
        ClientMapUser clientMapUser = new ClientMapUser();
        clientMapUser.setClientId(clientDetailsBo.getClientId());
        clientMapUser.setCompanyId(clientDetailsBo.getCompanyId());
        clientMapUser.setUserId("1");
        clientMapUser.setEnable(1);
        clientMapUser.setDelFlag(0);
        clientMapUser.setCreateTime(new Date());
        clientMapUser.setUpdateTime(new Date());
        clientMapUser.setUpdateBy(UserInfoContext.getUser().getId().toString());
        clientMapUser.setCreateBy(UserInfoContext.getUser().getId().toString());
        clientMapUserMapper.insertSelective(clientMapUser);
    }

    @Override
    public void bindUserToClient(OauthClientDetailsBo clientDetailsBo) {
        ClientMapUser clientMapUser = new ClientMapUser();
        clientMapUser.setClientId(clientDetailsBo.getClientId());
        clientMapUser.setCompanyId(clientDetailsBo.getCompanyId());
        clientMapUser.setUserId(clientDetailsBo.getUserId().toString());
        clientMapUser.setEnable(1);
        clientMapUser.setDelFlag(0);
        clientMapUser.setCreateTime(new Date());
        clientMapUser.setUpdateTime(new Date());
        clientMapUser.setUpdateBy(clientDetailsBo.getUpdateBy());
        clientMapUser.setCreateBy(clientDetailsBo.getCreateBy());
        clientMapUserMapper.insertSelective(clientMapUser);
    }


    @Override
    @Transactional
    public void addClientAndData(OauthClientDetailsBo clientDetailsBo) {
        OauthClientDetails oauthClientDetails = new OauthClientDetails();
        BeanUtils.copyProperties(clientDetailsBo, oauthClientDetails);
        this.addClient(oauthClientDetails);
        //绑定超管到应用 这里自带所有权限
        iOauthClientDetailsService.bindSuperadmin(clientDetailsBo);
        oauthClientDetails.setCompanyId(clientDetailsBo.getCompanyId());
        this.initClientAdminRole(oauthClientDetails);
        //给个人用户公司 赋值权限
        oauthClientDetails.setCompanyId(0);
        this.initClientAdminRole(oauthClientDetails);
    }

    @Override
    public void initClientAdminRole(OauthClientDetails oauthClientDetails) {
        Role adminRole = new Role();
        adminRole.setCompanyId(oauthClientDetails.getCompanyId());
        adminRole.setClientId(oauthClientDetails.getClientId());
        adminRole.setName(oauthClientDetails.getAdditionalInformation() + "系统管理员");
        adminRole.setCode("admin");
        iRoleService.addRole(adminRole);
        iResourcesService.giveAdminResources(adminRole);
    }

    @Override
    public List<OauthClientDetails> getCurrentCientList(Integer userId, Integer companyId) {
        List<OauthClientDetails> clientDetailsList = oauthClientDetailsMapper.getCurrentCientList(userId, companyId);
        return clientDetailsList;
    }

    @Override
    public List<OauthClientDetails> getIndexClientList() {
        OauthClientDetailsExample example = new OauthClientDetailsExample();
        example.createCriteria().andDelFlagEqualTo(0)
                .andCompanyIdEqualTo(1);
        List<OauthClientDetails> clientDetailsList = oauthClientDetailsMapper.selectByExample(example);
        return clientDetailsList;
    }

    @Override
    public void openClientSubmit(UserCore user) {
        ClientMapUserExample example = new ClientMapUserExample();
        example.createCriteria().andUserIdEqualTo(user.getId().toString())
                .andClientIdEqualTo(user.getClientId())
                .andCompanyIdEqualTo(user.getCompanyId());
        List<ClientMapUser> clientMapUserList = clientMapUserMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(clientMapUserList)) {
            ClientMapUser clientMapUser = clientMapUserList.get(0);
            if(clientMapUser.getEnable()==0){
                throw new ServiceException("申请审批中");
            }
            if(clientMapUser.getEnable()==-1){
                throw new ServiceException("申请不通过,请联系管理员");
            }
        }
        ClientMapUser clientMapUser = new ClientMapUser();
        clientMapUser.setClientId(user.getClientId());
        clientMapUser.setCompanyId(user.getCompanyId());
        clientMapUser.setEnable(0);
        clientMapUser.setUserId(user.getId().toString());
        clientMapUser.setCreateBy(user.getId().toString());
        clientMapUser.setUpdateBy(user.getId().toString());
        clientMapUser.setDelFlag(0);
        clientMapUser.setCreateTime(new Date());
        clientMapUser.setUpdateTime(new Date());
        clientMapUserMapper.insertSelective(clientMapUser);
    }
}
